home *** CD-ROM | disk | FTP | other *** search
- Path: EU.net!sun4nl!ittpub!ittpub!nntp
- Newsgroups: comp.lang.c++
- Subject: Re: Separate initization from Instantiation
- Message-ID: <1996Feb20.110543.1779@ittpub>
- From: wil@ittpub.nl (Wil Evers)
- Date: 20 Feb 96 11:05:43 WET
- References: <4g8l8s$e5q@reader2.ix.netcom.com>
- Distribution: world
- Nntp-Posting-Host: lintilla
-
- In article <4g8l8s$e5q@reader2.ix.netcom.com>
- pwallin@ix.netcom.com(Patrick Wallin ) writes:
-
- > I am researching on initization and instantiation in C++.
-
- [snip]
-
- > So I am trying to figure out how to allocate first and then later we
- > initialize something. I would appreciate if you could give me a short
- > example of it.
-
- To do this, you should understand the difference between a direct call to
- operator new()
-
- void *vp = operator new(sizeof *T);
-
- which simply allocates memory and returns a void * to it, and a
- `new-expression'
-
- T *tp = new T;
-
- which first allocates memory by a call to operator new() and then
- constructs an object in that memory, returning the address of the
- constructed object.
-
- Furthermore, you should know that it's possible to overload operator
- new(). Its first argument must be of type size_t and tells us how much
- memory to allocate, but we are free to declare versions of operator new()
- taking additional arguments. When called from a `new-expression' the first
- argument to operator new() is passed to us by the compiler, and the
- following ones are in between parentheses after the `new' keyword. If we
- write:
-
- T *tp = new (x) T;
-
- The compiler will call `operator new(sizeof(T), x)' before constructing an
- object of type T in the memory allocated.
-
- Finally, here's how this all adds up:
-
- // This version of operator new() simply returns the address we
- // pass to it in its second argument. It is often called
- // `placement new' and usually defined in <new.h>
- inline void *operator new(size_t, void *p)
- { return p; }
-
- class MyClass {
- ...
- public :
- MyClass(int arg1, int arg2);
- ...
- ~MyClass();
- };
-
- void f()
- {
- // get the memory we need by a direct call to
- // the default operator new()
- void *buf = operator new(sizeof MyClass);
-
- // .. do other things...
-
- // call a constructor by writing a `new-expression'
- // calling `placement new'
- MyClass *mcp = new (buf) MyClass(1, 2);
-
- // ...use *mcp...
- }
-
- Hope this helps,
-
- - Wil
-